package cn.net.wanji.task;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import cn.net.wanji.entity.InspectionStatus;
import cn.net.wanji.entity.VehicleRsuInfo;
import cn.net.wanji.mapper.DataReceiveMapper;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author guodejun
 * @createTime 2022/12/2 13:27
 * @description
 */
@Log4j2
@Component
@EnableScheduling   // 2.开启定时任务
public class MockData{

    @Resource
    DataReceiveMapper dataReceiveMapper;

    @Value("${mock.data}")
    private boolean mockData;

    @Value("${mock.file-path}")
    private String mockFilePath;

    private final String[] arr = {
            "G000511001000000111",
            "G000511001000000110",
            "G000511001000000112",
            "G000511001000000113",
            "G000511001000000114"
    };
    //       G000511001000110965 2022-09-26 20:00:0025

    private final String[] exceptions = {
            "010101",
            "010102",
            "010103",
            "010201",
            "010202",
            "010203",
            "010204",
            "010209",
            "010301",
            "010302",
            "010401",
            "010402",
            "010501"
    };

    private final int[] carType = {
            1,
            2,
            3,
            4,
            11,
            12,
            13,
            14,
            15,
            16
    };

    private final String[] licenseAbbre = {
            "陕",
            "川",
            "渝",
            "陇",
            "滇",
            "贵",
            ""
    };

    Random mRandom = new Random();


    @Scheduled(cron = "0 0 1 * * ?")
    public void run() throws Exception {
        // 插入数据
        if (!mockData) return;

        // 读取文件下所有 json 文件
        String basePath = mockFilePath;
        String[] fileNames = FileUtil.file(basePath).list();
        List<VehicleRsuInfo> vehicleRsuInfoList = new ArrayList<>();
        Arrays.stream(fileNames).forEach(item -> {
            String jsonText = new FileReader(basePath + item).readString();
            VehicleRsuInfo vehicleRsuInfo = JSONObject.parseObject(jsonText, VehicleRsuInfo.class);
            vehicleRsuInfoList.add(vehicleRsuInfo);

        });

        int sum = mRandom.nextInt(2000) + 2000;

        for (int j = 0; j < sum; j++) {
            // 为 5个 基站模拟 2 条正常车流、模拟一条异常车流
            int exception = 0;
            int normal = 0;
            for (String siteCode : arr) {
                int count = mRandom.nextInt(2);
                for (int i = 0; i < count; i++) {
                    insertException(siteCode, vehicleRsuInfoList);
                    exception++;
                    TimeUnit.MILLISECONDS.sleep(1000);
                }
                count = mRandom.nextInt(3);
                for (int i = 0; i < count; i++) {
                    insertNormal(siteCode, vehicleRsuInfoList);
                    normal++;
                    TimeUnit.MILLISECONDS.sleep(1000);
                }
            }
            log.info("mock data Exception: " + exception + ", Normal: " + normal);
        }


    }

    private void insertException(String siteCode, List<VehicleRsuInfo> vehicleRsuInfoList) {
        // 异常车流
        String[] dateInfo = getDateInfo();
        String recordId = siteCode + dateInfo[0];
        VehicleRsuInfo vehicleRsuInfo = createVehicleRsuInfo(vehicleRsuInfoList, recordId, dateInfo);
        int index = mRandom.nextInt(exceptions.length);
        String exception = exceptions[index];
        if (exception.contains("0104")) {
            vehicleRsuInfo.setLicenseCode("");
//            vehicleRsuInfo.setLicenseAbbre("");
        }
        vehicleRsuInfo.setErId(siteCode);
        vehicleRsuInfo.setUnlawfulMold(exception);
        dataReceiveMapper.insertVehicleRsuInfo(vehicleRsuInfo);
        // 添加 审核信息
        InspectionStatus inspectionStatus = new InspectionStatus();
        inspectionStatus.setRecordId(vehicleRsuInfo.getRecordId());
        inspectionStatus.setUnlawfulMold(vehicleRsuInfo.getUnlawfulMold());
        inspectionStatus.setCheckCondition("0");
        inspectionStatus.setConfidenceDegree(vehicleRsuInfo.getConfidenceDegree());
        dataReceiveMapper.insertInspectionStatus(inspectionStatus);
    }

    private void insertNormal(String siteCode, List<VehicleRsuInfo> vehicleRsuInfoList) {
        String[] dateInfo = getDateInfo();
        String recordId = siteCode + dateInfo[0];
        VehicleRsuInfo vehicleRsuInfo = createVehicleRsuInfo(vehicleRsuInfoList, recordId, dateInfo);
        vehicleRsuInfo.setUnlawfulMold("");
        vehicleRsuInfo.setErId(siteCode);
        dataReceiveMapper.insertVehicleRsuInfo(vehicleRsuInfo);
    }

    private static String[] getDateInfo() {
        String date = LocalDateTime.now().toString();
        String[] nowDate = date.split("T");
        String day = nowDate[0].replace("-", "") + nowDate[1].replace(":", "").replace(".", "");
        String replace = date.replace("T", " "); // 2022-12-02 13:43:52.373
        return new String[]{day, replace};
    }

    private VehicleRsuInfo createVehicleRsuInfo(List<VehicleRsuInfo> vehicleRsuInfoList, String recordId, String[] dateInfo) {
        int index = mRandom.nextInt(vehicleRsuInfoList.size());
        VehicleRsuInfo vehicleRsuInfo = vehicleRsuInfoList.get(index);
        vehicleRsuInfo.setIdentifyType(carType[mRandom.nextInt(carType.length)]);
        vehicleRsuInfo.setLicenseAbbre(licenseAbbre[mRandom.nextInt(licenseAbbre.length)]);
        vehicleRsuInfo.setRecordId(recordId);
        vehicleRsuInfo.setDriveDir(mRandom.nextInt(2) + 1);
        String[] split = dateInfo[1].split("\\.");
        vehicleRsuInfo.setHeadPicTime(split[0]);
        vehicleRsuInfo.setSidePicTime(split[0]);
        vehicleRsuInfo.setHourBatchNo(dateInfo[0]);
        vehicleRsuInfo.setEtcTransTime(split[0]);
        vehicleRsuInfo.setEtcEntryTime(split[0]);
        vehicleRsuInfo.setEtcEntryTime(split[0]);
        return vehicleRsuInfo;
    }


}
